<template>
  <n-h1>策略回测</n-h1>
  <n-form :model="model">
    <n-form-item label="名称"><n-input v-model:value="model.name" /></n-form-item>
    <n-form-item label="股票"><n-input v-model:value="model.codes" placeholder="sz000001,sz000002" /></n-form-item>
    <n-form-item label="开始"><n-date-picker v-model:value="model.start" type="date" /></n-form-item>
    <n-form-item label="结束"><n-date-picker v-model:value="model.end" type="date" /></n-form-item>
    <n-button @click="runBt">运行回测</n-button>
  </n-form>
  <n-p>状态：{{ status }}</n-p>
  <n-button v-if="nav.length" @click="downloadPdf">下载 PDF</n-button>
  <Line :data="chartData" :options="chartOpts" />
</template>

<script setup>
import { ref } from 'vue'
import { Line } from 'vue-chartjs'
import { Chart as ChartJS, Title, Tooltip, Legend, LineElement, CategoryScale, LinearScale } from 'chart.js'

ChartJS.register(Title, Tooltip, Legend, LineElement, CategoryScale, LinearScale)

const model = ref({ name: 'GridGNN', codes: 'sz000001,sz000002', start: Date.now() - 86400e3 * 365, end: Date.now() })
const status = ref('')
const nav = ref([])
const dates = ref([])

async function runBt() {
  const res = await fetch('/api/bt/run', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(model.value)
  })
  status.value = '已提交，后台运行中...'
  // 轮询结果
  const runId = (await res.json()).run_id
  const t = setInterval(async () => {
    const r = await fetch(`/api/bt/result/${runId}`)
    const j = await r.json()
    if (j.status === 'done') {
      clearInterval(t)
      nav.value = j.nav
      dates.value = j.dates
      status.value = `CAGR ${j.stats.cagr:.2%}  夏普 ${j.stats.sharpe:.2f}  最大回撤 ${j.stats.max_drawdown:.2%}`
    }
  }, 2000)
}

function downloadPdf() {
  // 用 jsPDF 生成 PDF（略）
}
</script>
